import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


# 自定义jwt_response_payload_handler函数修改返回值
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


# 判断用户输入的是手机号还是用户名
def username_mobile_login(username):
    try:
        # 如果是手机号
        if re.match(r'^1[3-9]\d{9}$', username):
            # 通过手机号查询用户
            user = User.objects.get(mobile=username)

        else:
            # 根据用户名查询用户
            user = User.objects.get(username=username)
    except User.DoesNOT.Exist:
        return None
    # 将对象返回
    return user


class UsernameMobileAuthBackend(ModelBackend):

    # 重写authenticate 方法添加手机号都登陆功能
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 　调用username_mobile_login，根据用户名和手机号获取用户对象
        user = username_mobile_login(username)

        # 如果用户存在且密码正确
        if user and user.check_password(password):
            return user
